package org.firefly.component;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component("quartz")
public class QuartzHealthIndicator implements HealthIndicator {

    private final Scheduler scheduler;

    public QuartzHealthIndicator(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    @Override
    public Health health() {
        try {
            if (scheduler == null) {
                return Health.down()
                        .withDetail("reason", "Scheduler not initialized")
                        .build();
            }

            if (scheduler.isShutdown()) {
                return Health.down()
                        .withDetail("reason", "Scheduler is shutdown")
                        .withDetail("since", formatDate(scheduler.getMetaData().getRunningSince()))
                        .build();
            }

            Health.Builder healthBuilder = Health.up()
                    .withDetail("schedulerName", scheduler.getSchedulerName())
                    .withDetail("instanceId", scheduler.getSchedulerInstanceId())
                    .withDetail("runningSince", formatDate(scheduler.getMetaData().getRunningSince()))
                    .withDetail("numberOfJobsExecuted", scheduler.getMetaData().getNumberOfJobsExecuted());

            try {
                healthBuilder
                        .withDetail("jobs", scheduler.getJobKeys(null).size())
                        .withDetail("triggers", scheduler.getTriggerKeys(null).size())
                        .withDetail("standbyMode", scheduler.isInStandbyMode());
            } catch (SchedulerException e) {
                healthBuilder.withDetail("detailError", "Failed to get detailed info: " + e.getMessage());
            }

            return healthBuilder.build();
        } catch (SchedulerException e) {
            return Health.down()
                    .withDetail("reason", "Scheduler exception: " + e.getMessage())
                    .build();
        }
    }

    private String formatDate(Date date) {
        return date != null ? date.toString() : "N/A";
    }
}